package com.wofish.web.controller.common;

import com.wofish.common.config.Global;
import com.wofish.common.config.ServerConfig;
import com.wofish.common.core.domain.AjaxResult;
import com.wofish.common.core.domain.UploadFile;
import com.wofish.common.utils.StringUtils;
import com.wofish.common.utils.file.FileSizeUtils;
import com.wofish.common.utils.file.FileUploadUtils;
import com.wofish.common.utils.file.FileUtils;
import com.wofish.goods.domain.Image;
import com.wofish.goods.service.IImageService;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通用请求处理
 * 
 * @author ruoyi
 */
@Controller
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    /**
     * 文件上传路径
     */
    public static final String UPLOAD_PATH = "/profile/upload/";

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IImageService imageService;

    /**
     * 通用下载请求
     * 
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Global.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/delete")
    @ResponseBody
    public AjaxResult deleteFile(String key) throws Exception {
        log.info(key);
        int row = imageService.deleteImageById(key);
        return AjaxResult.success("delete success:"+key+"row:"+row);
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile[] files) throws Exception
    {
        try
        {
            List<UploadFile> uploadFileList = new ArrayList<>();
            for(MultipartFile file : files){
                // 上传文件路径
                String filePath = Global.getUploadPath();
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);

                if(StringUtils.isBlank(fileName)){
                    return AjaxResult.error("error file");
                }

                String url = serverConfig.getUrl() + UPLOAD_PATH + fileName;

                Image image = new Image();
                String imageId = RandomStringUtils.randomAlphanumeric(32);
                image.setImageId(imageId);
                image.setUrl(url);
                image.setImageName(fileName);
                image.setIdent(url);
                image.setWatermark(0);
                image.setUpdateTime(new Date());
                imageService.insertImage(image);

                UploadFile uploadFile = new UploadFile();
                uploadFile.setFileName(fileName);
                uploadFile.setImageId(imageId);
                uploadFile.setUrl(url);
                uploadFile.setOriginalFilename(file.getOriginalFilename());
                uploadFile.setFileSize(FileSizeUtils.formatFileSize(file.getSize()));
                uploadFileList.add(uploadFile);
            }

           return AjaxResult.success(uploadFileList);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
